from views.base import BaseHandler
from db import db
import json
class RoleHandler(BaseHandler):
    def get(self):
        sql = "select * from roles"
        res = db.findAll(sql)
        self.finish({"code": 200,"msg":"获取成功", "data":res})
    # 添加角色
    def post(self):
        data = json.loads(self.request.body)
        name = data["name"]
        sql1 = "select * from roles where name = '%s'"%name
        res = db.findone(sql1)
        if res:
            self.write({"code": 200,"msg":"该角色已存在"})
        sql = "insert into roles(name) values ('%s')"%name
        db.add(sql)
        db.commit()
        self.write({"code": 200,"msg":"添加角色成功"})

# 获取所有按钮
class getpager(BaseHandler):
    def get(self):
        sql = "select * from pageresource"
        res = db.findAll(sql)
        return self.finish({"code": 200, "data":res})

# 获取所有页面
class getresou(BaseHandler):
    def get(self):
        sql = "select * from resource where type=1 and pid !=0;"
        res = db.findAll(sql)
        return self.finish({"code": 200, "data":res})

# 配置按钮
class addresou(BaseHandler):
    def post(self):
        data = json.loads(self.request.body)
        roleid = int(data["roleid"])
        resourceid = int(data["resourceid"])
        checkList = data["checkList"]
        print(checkList)
        sql1 = "delete from role_resource where userid=%d and resourceid=%d and page_resourceid is not null;"%(roleid,resourceid)
        db.add(sql1)
        db.commit()
        for i in checkList:
            sql = "insert into role_resource(userid, resourceid, page_resourceid) values (%d,%d,%d)"%(roleid,resourceid,int(i))
            print(sql)
            db.add(sql)
            db.commit()
        return self.finish({"code": 200, "msg": "配置成功"})

# 获取页面按钮权限
class Buttonqx(BaseHandler):
    def get(self):
        roleid = self.get_query_argument("roleid")
        url = self.get_query_argument("url")
        sql1 = "select * from resource where url='%s'"%(url)
        res1 = db.findone(sql1)
        id = res1["id"]
        sql ="select page_resourceid from role_resource where userid=%d and resourceid=%d  and page_resourceid is not null"%(int(roleid),int(id))
        res = db.findAll(sql)
        return self.finish({"code": 200, "data": res})